package vashion.azeroth.core.service.tran.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vashion.azeroth.common.common.check.FormatCheck;
import vashion.azeroth.common.date.DateUtil;
import vashion.azeroth.common.math.BigDecimalUtil;
import vashion.azeroth.common.push.util.JPushAlertUtils;
import vashion.azeroth.common.tran.GeneralOrderUtil;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.NeteaseSMSTemplateEnum;
import vashion.azeroth.contant.PushAlertEnum;
import vashion.azeroth.contant.TranErrorEnum;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.manager.item.BaseItemSkuManager;
import vashion.azeroth.core.manager.item.ItemReadManger;
import vashion.azeroth.core.manager.personal.config.ConfigCategoryTaxManager;
import vashion.azeroth.core.manager.personal.config.ConfigExchangeRateManager;
import vashion.azeroth.core.manager.personal.tran.PersonalDisburseManager;
import vashion.azeroth.core.manager.personal.tran.PersonalRechargeOrderManager;
import vashion.azeroth.core.manager.personal.tran.PersonalReturnGoodsOrderManager;
import vashion.azeroth.core.manager.personal.tran.PersonalSnapshotManager;
import vashion.azeroth.core.personal.pojo.ConfigCategoryTax;
import vashion.azeroth.core.personal.pojo.ConfigExchangeRate;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.personal.pojo.PersonalMemberVip;
import vashion.azeroth.core.personal.tran.pojo.PersonalBankInfo;
import vashion.azeroth.core.personal.tran.pojo.PersonalDisburse;
import vashion.azeroth.core.personal.tran.pojo.PersonalDisburseExt;
import vashion.azeroth.core.personal.tran.pojo.PersonalRechargeOrder;
import vashion.azeroth.core.personal.tran.pojo.PersonalReturnGoodsOrder;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshot;
import vashion.azeroth.core.personal.tran.pojo.PersonalSnapshotSku;
import vashion.azeroth.core.result.ApiResult;
import vashion.azeroth.core.service.PersonalMemberVipService;
import vashion.azeroth.core.service.base.BaseService;
import vashion.azeroth.core.service.impl.PersonalMemberServiceImpl;
import vashion.azeroth.core.service.item.ItemSkuService;
import vashion.azeroth.core.service.tran.PersonalCartsService;
import vashion.azeroth.core.service.tran.PersonalDisburseService;
import vashion.azeroth.core.service.tran.PersonalSnapshotService;
import vashion.azeroth.core.sms.NeteaseSMSSender;
import vashion.azeroth.task.job.PushJob;
import vashion.azeroth.task.job.SmsJob;
import vashion.azeroth.task.util.AsyncTaskExecutor;

import com.alibaba.fastjson.JSON;

@Service
public class PersonalDisburseServiceImpl extends BaseService implements PersonalDisburseService<PersonalDisburse> {

	private final static Logger log = LoggerFactory.getLogger(PersonalDisburseServiceImpl.class);

	@Autowired
	private PersonalDisburseManager disburseManager;
	@Autowired
	private PersonalSnapshotManager snapshotManager;
	@Autowired
	private PersonalSnapshotService snapshotService;
	@Autowired
	private ConfigCategoryTaxManager categoryTaxManager;
	@Autowired
	private PersonalReturnGoodsOrderManager returnGoodsOrderManager;
	@Autowired
	private BaseItemSkuManager baseItemSkuManager;
	@Autowired
	private ItemReadManger itemReadManger;
	@Autowired
	private PersonalMemberVipService<PersonalMemberVip> memberVipService;
	@Autowired
	private PersonalCartsService cartsService;
	@Autowired
	private PersonalMemberServiceImpl memberService;
	@Autowired
	private ConfigExchangeRateManager exchangeRateManager;
	@Autowired
	private PersonalRechargeOrderManager rechargeManager;
	@Autowired
	private NeteaseSMSSender smsSender;
	@Autowired
	private ItemSkuService itemSkuService;
	
	@Value("#{settings['expired']}")
	private Integer expired;
	@Value("#{settings['expired_close']}")
	private Integer expired_close;
	@Value("#{settings['recalculate_interval']}")
	private Integer recalculate_interval;
	
	@Value("#{settings['accountName']}")
	private String accountName;
	@Value("#{settings['accountNo']}")
	private String accountNo;
	@Value("#{settings['subBank']}")
	private String subBank;
	
	@Value("#{settings['unpayment_close']}")
	private Integer unpayment_close;
	
	@Value("#{settings['managerMemberId']}")
	private Long managerMemberId;

	/**
	 * 创建消费订单
	 */
	@Transactional
	@Override
	public ApiResult<String> createDisburse(PersonalMember buyerMmember, PersonalDisburse disburse) {
		
		disburse.setSkus(JSON.parseArray(disburse.getSnapshot().getProductQuantity(), PersonalSnapshotSku.class));
		
		snapshotService.fillingSnapshot(disburse);
		
		PersonalMember sellerMember = memberService.get(disburse.getSnapshot().getSupplierMemberId());
		
		ApiResult<ItemDO> itemDOResult = itemReadManger.getItemDetail(disburse.getSnapshot().getItemSkuDO().getItemId(), false);
    	ItemDO itemDO = itemDOResult.getData();
    	
    	ApiResult<ItemSkuDO> itemSkuDOResult = itemSkuService.getSkuDetail(disburse.getSnapshot().getItemSkuDO().getId());
    	ItemSkuDO itemSkuDO = itemSkuDOResult.getData();
    	
    	disburse.getSnapshot().setItemId(itemDO.getId());
    	disburse.getSnapshot().setTitle(itemDO.getBrandTitle());
    	disburse.getSnapshot().setItemDesc(itemDO.getItemDesc());
    	disburse.getSnapshot().setPic(itemDO.getPic());
    	disburse.getSnapshot().setCurno(itemDO.getPriceCurno());
    	disburse.getSnapshot().setRate(exchangeRateManager.getRate(disburse.getSnapshot().getCurno()));
    	disburse.getSnapshot().setMaterial(itemDO.getMaterial());
    	disburse.getSnapshot().setReferencePrice(itemDO.getReferencePrice());
    	disburse.getSnapshot().setColor(itemSkuDO.getColor());
    	disburse.getSnapshot().setItemCode(itemDO.getItemCode());
    	
    	//增加意大利商品信息
    	//结算价格
    	disburse.getSnapshot().setPrice(itemDO.getPrice());
    	disburse.getSnapshot().setPriceCny(exchangeRateManager.transferToCNY(disburse.getSnapshot().getCurno(), disburse.getSnapshot().getPrice()));
    	
		//非购买本供货商商品时需要溢价,重新计算商品价格
		if(!buyerMmember.getInviteMemberName().equals(sellerMember.getMemberName())) {
			//订单价格
	    	disburse.getSnapshot().setFinalPrice(itemReadManger.getHigherSupplierPrice(buyerMmember, itemDO));
	    	disburse.getSnapshot().setFinalPriceCny(exchangeRateManager.transferToCNY(disburse.getSnapshot().getCurno(), disburse.getSnapshot().getFinalPrice()));
		} else {
	    	disburse.getSnapshot().setFinalPrice(itemDO.getPrice());
	    	disburse.getSnapshot().setFinalPriceCny(exchangeRateManager.transferToCNY(disburse.getSnapshot().getCurno(), disburse.getSnapshot().getFinalPrice()));
		}
		
        buildDisburse(disburse, buyerMmember, sellerMember);
		disburseManager.save(disburse);
		
		disburse.getSnapshot().setSubDisburseNo(GeneralOrderUtil.generalSubDisburseNo("SDN", 6));
		disburse.getSnapshot().setDisburseNo(disburse.getDisburseNo());
		disburse.getSnapshot().setMemberId(disburse.getBuyerMemberId());
		disburse.getSnapshot().setStatus(AzerothConstants.PersonalSnapShot.SnapShotStatus.item_count_enouth);
		disburse.getSnapshot().setSupplierMemberId(Long.valueOf(sellerMember.getMemberId()));
		disburse.getSnapshot().setSupplierMemberName(sellerMember.getMemberName());
		snapshotManager.save(disburse.getSnapshot());
		
		if(null != sellerMember.getMobilePhone() && FormatCheck.isMobile(sellerMember.getMobilePhone())) {
			SmsJob job = new SmsJob(smsSender, sellerMember.getMobilePhone(), NeteaseSMSTemplateEnum.NEW_ORDER.getName(), buyerMmember.getNickName());
            AsyncTaskExecutor.submit(job);
		}
		
		PushJob job = new PushJob(sellerMember.getRegistrationId(), JPushAlertUtils.getAlertMsgReplace(PushAlertEnum.PUSH_CREATED.getAlertMsg(), buyerMmember.getNickName(), disburse.getDisburseNo()));
        AsyncTaskExecutor.submit(job);
		
		return ApiResult.newSuccessResult(disburse.getDisburseNo());
	}
	
	private int catQuantity(PersonalDisburse disburse) {
		int itemCount = 0;
		for (PersonalSnapshotSku sku : disburse.getSkus()) {
			itemCount += sku.getStock();
		}
		return itemCount;
	}
	
	private PersonalDisburse buildDisburse(PersonalDisburse disburse, PersonalMember member, PersonalMember supplierMember) {
		disburse.setDisburseNo(GeneralOrderUtil.generalDisburseNo("DN", 6));
		disburse.setBuyerMemberId(member.getMemberId());
		disburse.setBuyerMemberName(member.getMemberName());
		disburse.setBuyerNickName(member.getNickName());
		disburse.setSellerMemberId(supplierMember.getMemberId());
		disburse.setSellerMemberName(supplierMember.getMemberName());
		disburse.setSellerNickName(supplierMember.getNickName());
		disburse.getSnapshot().setQuantity(catQuantity(disburse));
	    //结算总价
		disburse.setTotalPrice(disburse.getSnapshot().getPriceCny() * disburse.getSnapshot().getQuantity());
		//订单总价
		disburse.setOrderTotalPrice(disburse.getSnapshot().getFinalPriceCny() * disburse.getSnapshot().getQuantity());
		disburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.created);
		disburse.setTimeAdd(new Date());
		disburse.setTimeEdit(new Date());
		return disburse;
	}

	@Override
	public PersonalDisburse getByDisburseNo(String disburseNo) {
		return disburseManager.getByDisburseNo(disburseNo);
	}

	@Override
	public ApiResult<List<PersonalDisburse>> queryOrder(PersonalDisburse disburse, Integer status) {
        PersonalMember member = memberService.get(disburse.getMemberId());
		if(null == member) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(), "用户" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		
		ApiResult<List<PersonalDisburse>> result = new ApiResult<List<PersonalDisburse>>();
		if(AzerothConstants.PersonalMember.MemberType.supplier.equals(member.getType())) {
			disburse.setSellerMemberId(disburse.getMemberId());
		} else if(AzerothConstants.PersonalMember.MemberType.agent.equals(member.getType())) {
			disburse.setBuyerMemberId(disburse.getMemberId());
		}
		disburse.setStatus(status);
		
        Integer count = disburseManager.findCnt(disburse);
        initPages(disburse, count);
        
		List<PersonalDisburse> orderList = disburseManager.find(disburse);
		
		if(null == orderList) {
			result.setData(null);
			result.setTotalCount(0);
			return result;
		} else {
			result.setData(orderList);
			result.setTotalCount(count);
		}
		
		return result;
	}
	
	@Override
	public ApiResult<List<PersonalDisburse>> queryOrderByNo(PersonalDisburse disburse) {
        
		ApiResult<List<PersonalDisburse>> result = new ApiResult<List<PersonalDisburse>>();
		List<PersonalDisburse> orderList = disburseManager.find(disburse);
		
		if(null == orderList) {
			result.setData(null);
			result.setTotalCount(0);
			return result;
		} else {
			result.setData(orderList);
			result.setTotalCount(1);
		}
		
		return result;
	}
	
	/**
	 * 更新订单状态
	 */
	@Override
	public ApiResult<Boolean> changeOrder(String disburseNo, String type) {
		PersonalDisburse disburse = disburseManager.getByDisburseNo(disburseNo);
		
		if(null == disburse) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(), "订单" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		
		PersonalMember buyerMember = memberService.get(disburse.getBuyerMemberId());
		PersonalMember sellerMember = memberService.get(disburse.getSellerMemberId());
		
		PersonalDisburse paramDisburse = new PersonalDisburse();
		
		//订单取消
		if(type.equalsIgnoreCase("agentOrderCancel")) {
			if(!disburse.getStatus().equals(AzerothConstants.PersonalDisburse.DisburseStatus.created) 
					&& !disburse.getStatus().equals(AzerothConstants.PersonalDisburse.DisburseStatus.supplier_accept)) {
				log.error("订单状态不正确不能取消," + disburse.getDisburseNo() + disburse.getStatus());
				return ApiResult.newErrorResult(GenericErrorEnum.STATUS_ERROR.getErrorCode(), "订单" + GenericErrorEnum.STATUS_ERROR.getErrorMessage());
			}
			paramDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.agent_order_cancel);
			
		//供货商拒绝
		} else if(type.equalsIgnoreCase("supplierRefuse")) {
			if(!disburse.getStatus().equals(AzerothConstants.PersonalDisburse.DisburseStatus.created)) {
				log.error("订单状态不正确不能确认收货," + disburse.getDisburseNo() + disburse.getStatus());
				return ApiResult.newErrorResult(GenericErrorEnum.STATUS_ERROR.getErrorCode(), "订单" + GenericErrorEnum.STATUS_ERROR.getErrorMessage());
			}
			paramDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.supplier_refuse);
		//供应商接单
		} else if(type.equalsIgnoreCase("supplierAccept")) {
			if(!disburse.getStatus().equals(0) && !disburse.getStatus().equals(2)) {
				log.error("订单状态不正确不能删除," + disburse.getDisburseNo() + disburse.getStatus());
				return ApiResult.newErrorResult(GenericErrorEnum.STATUS_ERROR.getErrorCode(), "订单" + GenericErrorEnum.STATUS_ERROR.getErrorMessage());
			}
			
			paramDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.supplier_accept);
			paramDisburse.setDisburseNo(disburseNo);
			paramDisburse.setTimeEdit(new Date());
			
			int count = disburseManager.update(paramDisburse);
			
			//减商品库存
			disburse.setSkus(JSON.parseArray(disburse.getSnapshot().getProductQuantity(), PersonalSnapshotSku.class));
			//减商品库存
			for (PersonalSnapshotSku sku : disburse.getSkus()) {
				if(!baseItemSkuManager.updateItemSkuNum(sku.getId(), sku.getStock(), Boolean.FALSE)) {
					log.error("商品库存不足,商品ID:" + sku.getId() + ", skuId:" + sku.getId() + ", 购买数量:" + sku.getStock());
				}
			}
			
			if(null != buyerMember.getMemberName() && FormatCheck.isMobile(buyerMember.getMemberName())) {
				SmsJob job = new SmsJob(smsSender, buyerMember.getMemberName(), NeteaseSMSTemplateEnum.ORDER_ACCEPTED.getName(), sellerMember.getNickName());
		        AsyncTaskExecutor.submit(job);
			}
			
			PushJob job = new PushJob(buyerMember.getRegistrationId(), JPushAlertUtils.getAlertMsgReplace(PushAlertEnum.PUSH_SUPPLIER_ACCEPT.getAlertMsg(), sellerMember.getNickName(), disburseNo));
	        AsyncTaskExecutor.submit(job);
			
			if(count > 0) {
				return ApiResult.newSuccessResult();
			} else {
				log.error("消费订单状态修改失败,订单号" + disburseNo);
				return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(), GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
			}
			
		//代理商付款
		} else if(type.equals("agentPayment")) {
			if(!disburse.getStatus().equals(3)) {
				log.error("订单状态不正确," + disburse.getDisburseNo() + disburse.getStatus());
				return ApiResult.newErrorResult(GenericErrorEnum.STATUS_ERROR.getErrorCode(), "订单" + GenericErrorEnum.STATUS_ERROR.getErrorMessage());
			}
			paramDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.agent_payment);
		//供货商发货
		} else if(type.equals("supplierSend")) {
			if(!disburse.getStatus().equals(4)) {
				log.error("订单状态不正确," + disburse.getDisburseNo() + disburse.getStatus());
				return ApiResult.newErrorResult(GenericErrorEnum.STATUS_ERROR.getErrorCode(), "订单" + GenericErrorEnum.STATUS_ERROR.getErrorMessage());
			}
			paramDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.supplier_send);
		}
		
		paramDisburse.setDisburseNo(disburseNo);
		paramDisburse.setTimeEdit(new Date());
		int count = disburseManager.update(paramDisburse);
		
		//代理商取消,发给供货商通知
		if(type.equalsIgnoreCase("agentOrderCancel")) {
			if(null != sellerMember.getMobilePhone() && FormatCheck.isMobile(sellerMember.getMobilePhone())) {
				SmsJob job = new SmsJob(smsSender, sellerMember.getMobilePhone(), NeteaseSMSTemplateEnum.ORDER_CANCELED.getName(), buyerMember.getNickName());
				AsyncTaskExecutor.submit(job);
			}

			PushJob job = new PushJob(sellerMember.getRegistrationId(), JPushAlertUtils.getAlertMsgReplace(PushAlertEnum.PUSH_AGENT_ORDER_CANCEL.getAlertMsg(), buyerMember.getNickName(), disburseNo));
			AsyncTaskExecutor.submit(job);
		//供货商拒绝,发给代理商通知
		} else if(type.equalsIgnoreCase("supplierRefuse")) {
			if(null != buyerMember.getMemberName() && FormatCheck.isMobile(buyerMember.getMemberName())) {
				SmsJob job = new SmsJob(smsSender, buyerMember.getMemberName(), NeteaseSMSTemplateEnum.ORDER_REJECTED.getName(), sellerMember.getNickName());
				AsyncTaskExecutor.submit(job);
			}
			
			PushJob job = new PushJob(buyerMember.getRegistrationId(), JPushAlertUtils.getAlertMsgReplace(PushAlertEnum.PUSH_SUPPLIER_REFUSE.getAlertMsg(), sellerMember.getNickName(), disburseNo));
			AsyncTaskExecutor.submit(job);
		//供货商发货,发给代理商通知
		} else if(type.equals("supplierSend")) {
			if(null != buyerMember.getMemberName() && FormatCheck.isMobile(buyerMember.getMemberName())) {
				SmsJob job = new SmsJob(smsSender, buyerMember.getMemberName(), NeteaseSMSTemplateEnum.ITEM_DELIVERED.getName(), sellerMember.getNickName());
				AsyncTaskExecutor.submit(job);
			}

			PushJob job = new PushJob(buyerMember.getRegistrationId(), JPushAlertUtils.getAlertMsgReplace(PushAlertEnum.PUSH_SUPPLIER_SEND.getAlertMsg(), sellerMember.getNickName(), disburseNo));
			AsyncTaskExecutor.submit(job);
		}
		
		if(count > 0) {
			return ApiResult.newSuccessResult();
		}
		
		log.error("消费订单状态修改失败,订单号" + disburseNo);
		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(), GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	@Override
	public ApiResult<String> modifyDisburseAddress(PersonalDisburse disburse) {
		
		PersonalDisburse disburseDb = disburseManager.getByDisburseNo(disburse.getDisburseNo());
		if(null == disburseDb) {
			log.error("消费订单不存在,订单号" + disburse.getDisburseNo());
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(), "消费订单" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		if(disburseDb.getBuyerMemberId() != disburse.getBuyerMemberId()) {
			log.error("不能修改其它人订单,订单号" + disburse.getDisburseNo() + ", 修改人memberId:" + disburse.getBuyerMemberId());
			return ApiResult.newErrorResult(TranErrorEnum.NOT_MODIFY_OTHER_ORDER.getErrorCode(), TranErrorEnum.NOT_MODIFY_OTHER_ORDER.getErrorMessage());
		}
		
		PersonalDisburse paramDisburse = new PersonalDisburse();
		paramDisburse.setDisburseNo(disburse.getDisburseNo());
		paramDisburse.setAddressDetail(disburse.getAddressDetail());
		paramDisburse.setReceiveName(disburse.getReceiveName());
		paramDisburse.setPhone(disburse.getPhone());
		paramDisburse.setTimeEdit(new Date());
		
		int count = disburseManager.update(paramDisburse);
		if(count > 0)
			return ApiResult.newSuccessResult();
		
		log.error("更新消费订单收货地址接口异常,订单号" + disburse.getDisburseNo());
		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(), GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	@Override
	public ApiResult<List<PersonalDisburseExt>> getDisburseList(PersonalDisburseExt disburse) {
		ApiResult<List<PersonalDisburseExt>> result = new ApiResult<List<PersonalDisburseExt>>();
		int totalCount = disburseManager.getDisburseListCnt(disburse);
		initPages(disburse, totalCount);
        List<PersonalDisburseExt> orderList = disburseManager.getDisburseList(disburse);
        
        for (PersonalDisburse personalDisburse : orderList) {
			if(null != personalDisburse.getSnapshots()) {
				snapshotService.fillingSnapshot(personalDisburse.getSnapshots());
			}
		}
        
        result.setData(orderList);
        result.setTotalCount(totalCount);
		
		return result;
	}
	
	@Override
	public List<PersonalDisburseExt> queryDisburseList(PersonalDisburseExt disburse) {

        List<PersonalDisburseExt> orderList = disburseManager.getDisburseList(disburse);
		return orderList;
	}

	@Override
	public ApiResult<String> sendGoods(PersonalDisburse disburseParam) {
		
		PersonalDisburse disburse =  disburseManager.getByDisburseNo(disburseParam.getDisburseNo());
		disburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.supplier_send);
		disburse.setLogisticsCompany(disburseParam.getLogisticsCompany());
		disburse.setLogisticsNo(disburseParam.getLogisticsNo());
		disburse.setTimeSendGoods(new Date());
		disburse.setTimeEdit(new Date());
		
		int count = disburseManager.update(disburse);
		
		if(count > 0) {
			return ApiResult.newSuccessResult();
		}
		
		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(), GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	
	@Override
	public ApiResult<PersonalDisburse> queryReturnGoodsInfo(Long memberId, String disburseNo) {
		
		PersonalDisburse disburse = disburseManager.getByDisburseNo(disburseNo);
		if(null == disburse) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(), "订单" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		if(disburse.getBuyerMemberId() != memberId) {
			return ApiResult.newErrorResult(TranErrorEnum.NOT_MODIFY_OTHER_ORDER.getErrorCode(), TranErrorEnum.NOT_MODIFY_OTHER_ORDER.getErrorMessage());
		}
		
		/**
		 * 计算商品可退款金额
		 */
		for (PersonalSnapshot snapshot : disburse.getSnapshots()) {
			ConfigCategoryTax categoryTax = categoryTaxManager.get(snapshot.getCategoryId());
			if(null == categoryTax) {
				snapshot.setRefundAmount(snapshot.getPrice());
			} else {
				long tax = BigDecimalUtil.multiply(new BigDecimal(snapshot.getPrice()), categoryTax.getRate()).longValue();
				snapshot.setRefundAmount(snapshot.getPrice() - tax);
			}
		}
		return ApiResult.newSuccessResult(disburse);
		
	}

	@Transactional
	@Override
	public ApiResult<String> submitReturnGoodsApply(PersonalSnapshot snapshot) {
		
		PersonalDisburse disburse = disburseManager.getByDisburseNo(snapshot.getDisburseNo());
		if(null == disburse) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EXIST.getErrorCode(), "订单" + GenericErrorEnum.NOT_EXIST.getErrorMessage());
		}
		
//		if(disburse.getStatus() != (AzerothConstants.PersonalDisburse.DisburseStatus.buyer_received)) {
//			return ApiResult.newErrorResult(TranErrorEnum.NOT_CONFIRM_RECEIVED.getErrorCode(), TranErrorEnum.NOT_CONFIRM_RECEIVED.getErrorMessage());
//		}
		
		//finished这里有个BUG
//		if(DateUtil.compare(new Date(), disburse.getTimeFinished(), DateUtil.ONE_DAY) < 15) {
//			return ApiResult.newErrorResult(TranErrorEnum.TIME_NOT_ENOUGH_RETURN_GOODS.getErrorCode(), TranErrorEnum.TIME_NOT_ENOUGH_RETURN_GOODS.getErrorMessage());
//		}
		
		PersonalSnapshot dbsnapshot = snapshotManager.getSnapshot(snapshot);
		
		if(null == dbsnapshot) {
			return ApiResult.newErrorResult(TranErrorEnum.DISBURSE_ORDER_STATUS_ERROR.getErrorCode(), "商品" + TranErrorEnum.DISBURSE_ORDER_STATUS_ERROR.getErrorMessage());
		}
		
		if(StringUtils.isBlank(dbsnapshot.getReturnGoodsNo())) {
			//获取类目关税
			ApiResult<ItemDO> retult = itemReadManger.getItemDetail(dbsnapshot.getItemId(), Boolean.FALSE);
			ItemDO item = retult.getData();
			
			Long returnPrice = snapshotService.calTariff(item, dbsnapshot.getPrice());
			
			returnGoodsOrderManager.save(buildReturnGoodsOrder(dbsnapshot, returnPrice*dbsnapshot.getQuantity(), item.getTariff()));
			return ApiResult.newSuccessResult();
		} else if(dbsnapshot.getStatus() == AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.return_goods_cancel) {
			PersonalReturnGoodsOrder orderParam = new PersonalReturnGoodsOrder();
			orderParam.setReturnGoodsNo(dbsnapshot.getReturnGoodsNo());
			orderParam.setStatus(AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.return_goods_apply);
			orderParam.setTimeEdit(new Date());
			returnGoodsOrderManager.update(orderParam);
			return ApiResult.newSuccessResult();
		} else {
			return ApiResult.newErrorResult(TranErrorEnum.NOT_REPEAT_RETURN_GOODS.getErrorCode(), TranErrorEnum.NOT_REPEAT_RETURN_GOODS.getErrorMessage());
		}
		
	}
	
	public PersonalReturnGoodsOrder buildReturnGoodsOrder(PersonalSnapshot snapshot, long returnPrice, BigDecimal tariff) {
		PersonalReturnGoodsOrder returnGoodsOrder = new PersonalReturnGoodsOrder();
		returnGoodsOrder.setReturnGoodsNo(GeneralOrderUtil.generalReturnGoodsOrderNo("RG", 6));
		returnGoodsOrder.setDisburseNo(snapshot.getDisburseNo());
		returnGoodsOrder.setMemberId(snapshot.getMemberId());
		returnGoodsOrder.setItemId(snapshot.getItemId());
		returnGoodsOrder.setQuantity(snapshot.getQuantity());
		returnGoodsOrder.setSkuId(snapshot.getSkuId());
		returnGoodsOrder.setRate(tariff);
		returnGoodsOrder.setRefundAmount(returnPrice);
		returnGoodsOrder.setFare(0);
		returnGoodsOrder.setStatus(AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.return_goods_apply);
		returnGoodsOrder.setTimeAdd(new Date());
		returnGoodsOrder.setTimeEdit(new Date());
		returnGoodsOrder.setRemark(String.valueOf(snapshot.getPrice()));
		
		return returnGoodsOrder;
	}

	@Transactional
	@Override
	public ApiResult<String> cancelReturnGoodsApply(PersonalSnapshot snapshot) {
		
		if(StringUtils.isBlank(snapshot.getReturnGoodsNo())) {
			return ApiResult.newErrorResult(GenericErrorEnum.NOT_EMPTY.getErrorCode(), "支付密码" + "退货订单号" + GenericErrorEnum.NOT_EMPTY.getErrorMessage());
		}
		
		PersonalReturnGoodsOrder returnGoodsOrder = returnGoodsOrderManager.get(snapshot.getReturnGoodsNo());
		
		if(null == returnGoodsOrder) {
			return ApiResult.newErrorResult(GenericErrorEnum.ORDER_NOT_EXIST.getErrorCode(), GenericErrorEnum.ORDER_NOT_EXIST.getErrorMessage());
		}
		
		if(returnGoodsOrder.getStatus() != AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.return_goods_apply 
				&& returnGoodsOrder.getStatus() != AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.return_goods_apply_agree) {
			return ApiResult.newErrorResult(TranErrorEnum.DISBURSE_ORDER_STATUS_ERROR.getErrorCode(), "退货" + TranErrorEnum.DISBURSE_ORDER_STATUS_ERROR.getErrorMessage());
		}
		
		PersonalReturnGoodsOrder returnGoodsOrderParam = new PersonalReturnGoodsOrder();
		returnGoodsOrderParam.setReturnGoodsNo(returnGoodsOrder.getReturnGoodsNo());
		returnGoodsOrderParam.setStatus(AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.return_goods_cancel);
		
	    returnGoodsOrderManager.update(returnGoodsOrderParam);
		
		return ApiResult.newSuccessResult();
	}

	@Override
	public void closeOrder() {
		PersonalDisburse disburseParam = new PersonalDisburse();
		disburseParam.setTimeAdd(DateUtil.addMinute(new Date(), -expired_close*60));
		disburseParam.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.created);
		
		List<PersonalDisburse> disburseList = disburseManager.findAll(disburseParam);
		for (PersonalDisburse personalDisburse : disburseList) {
			personalDisburse.setTimeEdit(new Date());
			personalDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.timeout_close);
			personalDisburse.setRemark("接单超时关闭");
			disburseManager.update(personalDisburse);
		}
	}
	
	@Override
	public void closeUnpaymentOrder() {
		PersonalDisburse disburseParam = new PersonalDisburse();
		disburseParam.setTimeAdd(DateUtil.addMinute(new Date(), -unpayment_close*60));
		disburseParam.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.supplier_accept);
		
		List<PersonalDisburse> disburseList = disburseManager.findAll(disburseParam);
		for (PersonalDisburse personalDisburse : disburseList) {
			
			//加商品库存
			personalDisburse.setSkus(JSON.parseArray(personalDisburse.getSnapshot().getProductQuantity(), PersonalSnapshotSku.class));
			
			//减商品库存
			for (PersonalSnapshotSku sku : personalDisburse.getSkus()) {
				if(!baseItemSkuManager.updateItemSkuNum(sku.getId(), sku.getStock(), Boolean.TRUE)) {
					log.error("加库存失败,商品ID:" + sku.getId() + ", skuId:" + sku.getId() + ", 购买数量:" + sku.getStock());
				}
			}
			
			personalDisburse.setTimeEdit(new Date());
			personalDisburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.timeout_close);
			personalDisburse.setRemark("付款超时关闭");
			disburseManager.update(personalDisburse);
		}
	}

	@Override
	public ApiResult<String> submitLogisticsInfo(String returnGoodsNo, String logisticsCompany, String logisticsNo) {
		PersonalReturnGoodsOrder returnGoodsOrder = new PersonalReturnGoodsOrder();
		returnGoodsOrder.setReturnGoodsNo(returnGoodsNo);
		returnGoodsOrder.setLogisticsCompany(logisticsCompany);
		returnGoodsOrder.setLogisticsNo(logisticsNo);
		returnGoodsOrder.setStatus(AzerothConstants.PersonalReturnGoodsOrder.ReturnGoodsOrderStatus.buyer_return_goods);
		returnGoodsOrder.setTimeEdit(new Date());
		int count = returnGoodsOrderManager.update(returnGoodsOrder);
		if(count > 0)
			return ApiResult.newSuccessResult();
		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(), GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	@Override
	public void recalculate() {
		List<ConfigExchangeRate> rateList = exchangeRateManager.findAllEnable();
		
		Map<String, ConfigExchangeRate> rateMap = new HashMap<String, ConfigExchangeRate>();
		for (ConfigExchangeRate rate : rateList) {
			rateMap.put(rate.getCurno(), rate);
		}
		
		PersonalDisburse param = new PersonalDisburse();
		
		param.setTimeAdd(DateUtils.addDays(new Date(), -1*recalculate_interval));
		List<PersonalDisburse> ordersList = disburseManager.findRecalculateOrder(param);
		
		if(null == ordersList || ordersList.size() == 0) return;
			
		for (PersonalDisburse disburse : ordersList) {
			try {
				PersonalMember buyerMmember = memberService.get(disburse.getBuyerMemberId());
				PersonalSnapshot snapshot = disburse.getSnapshot();
				//商品汇率为人民币时不需要重算
				if(snapshot.getCurno().equalsIgnoreCase("cny")) {
					continue;
				}
				//当前汇率大于下单时汇率时需重算订单价格
				if(BigDecimalUtil.greaterThan(rateMap.get(snapshot.getCurno()).getCnsell(), snapshot.getRate())) {
					log.info("订单" + disburse.getDisburseNo() + "重新计算价格");
					ApiResult<ItemDO> itemDOResult = itemReadManger.getItemDetail(snapshot.getItemId(), false);
			    	ItemDO itemDO = itemDOResult.getData();
					snapshot.setRateOld(snapshot.getRate());
					snapshot.setRate(rateMap.get(snapshot.getCurno()).getCnsell());
					
					if(!buyerMmember.getInviteMemberId().equals(itemDO.getUserId())) {
						//订单价格
						snapshot.setFinalPrice(itemReadManger.getHigherSupplierPrice(buyerMmember, itemDO));
						snapshot.setFinalPriceCny(exchangeRateManager.transferToCNY(snapshot.getCurno(), snapshot.getFinalPrice()));
					} else {
						snapshot.setFinalPrice(itemDO.getPrice());
						snapshot.setFinalPriceCny(exchangeRateManager.transferToCNY(snapshot.getCurno(), snapshot.getFinalPrice()));
					}
					
					snapshotManager.update(snapshot);
					
					//订单总价
					disburse.setOrderTotalPrice(snapshot.getFinalPriceCny() * snapshot.getQuantity());
					disburse.setTimeEdit(new Date());
					disburseManager.update(disburse);
					
					//汇率变化重算订单金额时，如已创建过充值订单，需要更新充值订单金额，实际付款时发送到ping++的数据取充值订单金额
					PersonalRechargeOrder rechargeOrder = rechargeManager.getRechargeOrderByDisburseNo(disburse.getDisburseNo());
					if(null != rechargeOrder) {
						log.info("重算订单价格更新充值订单金额");
						rechargeOrder.setAmount(disburse.getOrderTotalPrice());
						rechargeManager.update(rechargeOrder);
					}
				}
				
			} catch(Exception e) {
				log.error("重新计算消息订单金额异常", e);
			}
			
		}
	}

	@Override
	public ApiResult<String> uploadCertificatePic(PersonalDisburse disburse) {
		disburse.setStatus(AzerothConstants.PersonalDisburse.DisburseStatus.certificate_uploaded);
		disburse.setTimeEdit(new Date());
		int result = disburseManager.update(disburse);
		
		PersonalMember managerMember = memberService.get(managerMemberId);
		
		if(null != managerMember.getMobilePhone() && FormatCheck.isMobile(managerMember.getMobilePhone())) {
			SmsJob job = new SmsJob(smsSender, managerMember.getMobilePhone(), NeteaseSMSTemplateEnum.CERTIFICATE_UPLOADED.getName(), disburse.getDisburseNo());
			AsyncTaskExecutor.submit(job);
		}

		PushJob job = new PushJob(managerMember.getRegistrationId(), JPushAlertUtils.getAlertMsgReplace(PushAlertEnum.PUSH_CERTIFICATE_UPLOADED.getAlertMsg(), disburse.getDisburseNo(), disburse.getDisburseNo()));
		AsyncTaskExecutor.submit(job);
		
		if(result > 0) {
			return ApiResult.newSuccessResult();
		}
		
		return ApiResult.newErrorResult(GenericErrorEnum.UPDATE_ERROR.getErrorCode(), GenericErrorEnum.UPDATE_ERROR.getErrorMessage());
	}

	@Override
	public ApiResult<PersonalBankInfo> queryBankInfo(Long memberId) {
		PersonalBankInfo bankInfo = new PersonalBankInfo();
		bankInfo.setAccountName(accountName);
		bankInfo.setAccountNo(accountNo);
		bankInfo.setSubBank(subBank);
		
		return ApiResult.newSuccessResult(bankInfo);
	}


}
